package judesart.app.client.ui.admin.profile;

import java.util.List;

import judesart.app.client.controller.ExhibitionController;
import judesart.app.client.controller.ExhibitionControllerAsync;
import judesart.app.domain.Address;
import judesart.app.domain.Exhibition;
import judesart.app.shared.SearchResult;

import com.allen_sauer.gwt.log.client.Log;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ListLoader;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Composite;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.ListView;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class ExhibitionsPanel extends Composite {
    ExhibitionControllerAsync service = ExhibitionController.Util.getInstance();
    ContentPanel listPanel;
    private final ExhibitionDetailPanel detailsPanel;
    static final DateTimeFormat formater = DateTimeFormat.getFormat("EEE, MMMM dd, yyyy");
    private final ListLoader<ListLoadResult<Exhibition>> loader;

    public ExhibitionsPanel() {
        final ContentPanel mainPanel = new ContentPanel();
        mainPanel.setHeaderVisible(false);
        mainPanel.setFrame(false);
        mainPanel.setBorders(false);

        RpcProxy<List<Exhibition>> proxy = new RpcProxy<List<Exhibition>>() {
            @Override
            protected void load(Object loadConfig,
                    final AsyncCallback<List<Exhibition>> callback) {
                Log.debug(" > Load exhibitions");
                getExhibitions(callback);
            }
        };

        loader = new BaseListLoader<ListLoadResult<Exhibition>>(proxy, new BeanModelReader());
        ListStore<BeanModel> store = new ListStore<BeanModel>(loader);
        loader.load();

        listPanel = new ContentPanel();
        listPanel.setCollapsible(false);
        listPanel.setAnimCollapse(false);
        listPanel.setFrame(true);
        listPanel.setId("id-jaw-ExhibitionsPanel-list");
        listPanel.setHeading("Exhibitions");
        listPanel.setWidth(800);
        listPanel.setHeight(513);
        listPanel.setBodyBorder(false);

        ListView<BeanModel> view = new ListView<BeanModel>() {
            @Override
            protected BeanModel prepareData(BeanModel model) {
                loadPrepareData(model);
                return model;
            }
        };

        view.setTemplate(getTemplate());
        view.setStore(store);
        view.setItemSelector("div.thumb-wrap");
        view.getSelectionModel().addListener(Events.SelectionChange,
                new Listener<SelectionChangedEvent<BeanModel>>() {

                    public void handleEvent(SelectionChangedEvent<BeanModel> be) {
                        Log.debug(" handleEvent Selection ["
                                + be.getSelection().size() + "]");
                        if (be.getSelection().size() > 0) {
                            Log.debug(" handleEvent 0 ["
                                    + be.getSelection().get(0).get("id") + "]");
                            open((Long) be.getSelection().get(0).get("id"));
                        }
                    }

                });
        view.setBorders(false);
        view.setHeight(430);
        listPanel.add(view);

        Button btnAddNew = new Button("Add New");
        btnAddNew.addSelectionListener(new SelectionListener<ButtonEvent>() {
            @Override
            public void componentSelected(ButtonEvent ce) {
                open(null);
            }
        });
        listPanel.addButton(btnAddNew);
        listPanel.setButtonAlign(HorizontalAlignment.RIGHT);
        mainPanel.add(listPanel);
        detailsPanel = new ExhibitionDetailPanel(this);
        mainPanel.add(detailsPanel);
        initComponent(mainPanel);
        final Timer hideDetailsPanelTimer = new Timer() {
            @Override
            public void run() {
                detailsPanel.hide();
            }
        };
        hideDetailsPanelTimer.schedule(200);
    }

    public void open(Long id) {
        detailsPanel.open(id);
        listPanel.hide();
        detailsPanel.show();
    }

    public void list() {
        detailsPanel.hide();
        loader.load();
        listPanel.show();
    }

    private void getExhibitions(final AsyncCallback<List<Exhibition>> callback) {
        service.searchExhibitions(0, 500,
                new AsyncCallback<SearchResult<Exhibition>>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        callback.onFailure(caught);
                    }

                    public void onSuccess(SearchResult<Exhibition> result) {
                        callback.onSuccess(result.getResults());
                    };
                });
    }

    private BeanModel loadPrepareData(BeanModel model) {
        Exhibition e = model.getBean();
        if (e.getStartDate() != null)
            model.set("startDateFormated", formater.format(e.getStartDate()));
        if (e.getEndDate() != null)
            model.set("endDateFormated", formater.format(e.getEndDate()));
        if (e.getPhotos() != null && e.getPhotos().size() > 0)
            model.set("photoId", e.getPhotos().get(0).getImageId().toString());
        Address address = e.getGalleryAddress();
        if (address != null && address.getCity() != null
                && address.getCity().trim().length() > 0
                && address.getCountry() != null) {
            model.set("location", address.getCity() + ", "
                    + address.getCountry().title());
        }
        return model;
    }

    private native String getTemplate() /*-{
        return ['<tpl for=".">', 
        '<div style="" class="thumb-wrap" id="{id}">', 
        '<span class="thumb"><img src="/image?id={photoId}&size=100x100&crop=true" title="{title}"/></span>',
        '<span class="thumb-legend">',
        '<span class="dates">{startDateFormated} - {endDateFormated}</span>',
        '<span class="location">{location}</span>',
        '<span class="title">{title}</span>',
        '</span>', 
        '<div class="x-clear"></div>',
        '</div>',
        '</tpl>', 
        '<div class="x-clear"></div>'].join("");
    }-*/;
}
